<?php

require_once("track.inc.php");
require_once("database.inc.php");
require_once("ad.inc.php");
require_once("functions.inc.php");
require_once("HT_Client/HT_Client.class.php");
error_reporting(E_ERROR | E_WARNING | E_PARSE);

$dbh = connect_db();

$beenthere = array();
$beenhere = array();
$forteam = "";
$forteamid = "";

$login = "";
$seccode = "";

if (isset($_POST['login']) && isset($_POST['seccode'])) {
	$login = $_POST['login'];
	$seccode = $_POST['seccode'];
#	if (isset($_POST['uhoc']) && $_POST['uhoc'] === "on") $uhoc = true;
	$uhoc = true;
#	else $uhoc = false;
	if (isset($_POST['teamid']) && is_numeric($_POST['teamid']) && $_POST['teamid'] > 0) $teamid = $_POST['teamid'];
} 

/*
if ($uhoc) {
	if (!$sema = mysql_query("SELECT UNIX_TIMESTAMP(since) stamp FROM flags_semaphore", $dbh)) die (mysql_error());
	$semarow = mysql_fetch_array($sema);
	if (mysql_num_rows($sema) > 0 && $semarow['stamp'] < 600) $uhoc = false;
}
*/


//if there is a username and security code provided, try fetching flags with those credentials
if ($login !== "" && $seccode !== "") {
	$agent = "Coolness calculator V2.0";
	$client = new HT_Client($agent);
        if (!$client->Login($login,$seccode,$agent)) die ("Could not log in. Is your security code correct? If so, there may be a problem with Hattrick and you will have to try again later.\n");
	$now = date("Y-m-d H:i:s");
	if (isset($teamid)) { //if a teamid is specified, get its flags
		coolhit($now, $login, $uhoc, $teamid);
		$flags = $client->getFlags($teamid);
	} else { //otherwise, get logged in user's flags
		coolhit($now, $login, $uhoc);
		$flags = $client->getFlags();
	}

	if (!isset($flags['info']['userid'])) {
		die ("Something is wrong with that team, or Hattrick bugged.\n");
	} else if ($flags['info']['teamid'] == 0) {
		die ("That team does not exist!");
	} else if ($flags['info']['userid'] == 0) {
		mysql_query("DELETE FROM flags_updated WHERE teamid = {$flags['info']['teamid']}", $dbh);
		die ("That is an ownerless team! If it was in the <a href=\"hallofcool.php\">Hall of Cool</a>, it has now been removed.\n");
	} else {
		if (!isset($teamid) && !isset($_GET['cleanup'])) setcookie("own_teamid", $flags['info']['teamid'], time()+60*60*24*28);
		$forteam = "for {$flags['info']['teamname']} ({$flags['info']['teamid']})";
		$forteamid = $flags['info']['teamid'];
		$query = mysql_query("SELECT SUM(activeusers) AS active FROM leagues_daily WHERE leagueid != 255", $dbh);
		while ($row = mysql_fetch_array($query)) {
			$numactive = $row['active'];
		}

		if (!$lquery = mysql_query("SELECT leagueid FROM leagues_daily WHERE leagueid != 255", $dbh)) die (mysql_error());
		/*
		while ($lrow = mysql_fetch_array($lquery)) {
			mysql_query("INSERT IGNORE INTO flags_v2 VALUES ({$flags['info']['userid']}, {$lrow['leagueid']}, 0, 0)", $dbh);
			mysql_query("INSERT IGNORE INTO flags_v2 VALUES ({$flags['info']['userid']}, {$lrow['leagueid']}, 1, 0)", $dbh);
		}
		*/
		foreach (array_keys($flags['away']) as $flag) {
			$sql = "INSERT INTO flags_v3 
						(user_id, league_id, home, away)
					VALUES 
						('".$flags['info']['userid']."', '".$flag."', 0, 1)
					ON DUPLICATE KEY 
						UPDATE away = 1";
			mysql_query($sql, $dbh);
			//mysql_query("REPLACE INTO flags_v2 VALUES ({$flags['info']['userid']}, $flag, 0)", $dbh);
		}
		foreach (array_keys($flags['home']) as $flag) {
			$sql = "INSERT INTO flags_v3 
						(user_id, league_id, home, away)
					VALUES 
						('".$flags['info']['userid']."', '".$flag."', 1, 0)
					ON DUPLICATE KEY 
						UPDATE home = 1";
			mysql_query($sql, $dbh);
			//mysql_query("REPLACE INTO flags_v2 VALUES ({$flags['info']['userid']}, $flag, 1)", $dbh);
		}

		if (!mysql_query("REPLACE INTO flags_updated VALUES (
			{$flags['info']['teamid']},\"" .
			mysql_real_escape_string($flags['info']['teamname'],$dbh) . "\",
			{$flags['info']['leagueid']},
			{$flags['info']['regionid']},
			{$flags['info']['userid']},
			\"{$flags['info']['loginname']}\",
			{$flags['info']['serieid']},
			{$flags['info']['hassupporter']},
			{$flags['info']['languageid']},
			{$flags['info']['stillincup']},
			\"{$flags['info']['signupdate']}\",
			\"{$flags['info']['activationdate']}\",
			\"{$flags['info']['lastlogindate']}\",
			\"$now\"
		)", $dbh)) die(mysql_error());

		if ($uhoc) {
/*			if (!$sema = mysql_query("SELECT UNIX_TIMESTAMP(since) stamp FROM flags_semaphore", $dbh)) die (mysql_error());
			$semarow = mysql_fetch_array($sema);
			if (mysql_num_rows($sema) > 0 && $semarow['stamp'] < 600) {
?>
<html>
<head>
<title>Hall of Cool refresh delayed</title>
<meta http-equiv="Refresh" content="30;URL=http://websec.science.uva.nl/~lhoek/coolness.php?tid=<?php echo $flags['info']['teamid']; ?>" />
</head>
<body>
Your data has been updated successfully, but because someone else was refreshing the Hall of Cool, your request to refresh it was canceled. Since you are seeing this message, the site is probably quite busy, and the Hall of Cool will be refreshed by someone else within minutes; the last refresh attempt was at <?php echo $lasthocupdate; ?>. If you can't wait that long, feel free to resubmit your team.<br /><br />
You will be returned to the Coolness calculator automatically within 30 seconds, or you can <a href="http://websec.science.uva.nl/~lhoek/coolness.php?tid=<?php echo $flags['info']['teamid']; ?>">click here</a>.
</body>
</html>
<?php

				die();
			} else { */
				if (!mysql_query("REPLACE INTO flags_semaphore VALUES ({$flags['info']['teamid']}, NOW())", $dbh)) die (mysql_error());
				if (!mysql_query("REPLACE INTO flags_both 
					SELECT userid, leagueid
					FROM flags_v3 f
					WHERE f.userid = {$flags['info']['userid']}
					AND home = 1 AND away = 1", $dbh)) die (mysql_error());
				if (!mysql_query("REPLACE INTO flags_ranking 
					SELECT f.userid userid, home, ROUND( SUM( $numactive / activeusers ) ) coolness, COUNT( DISTINCT f.leagueid ) num
					FROM flags_v3 f, leagues_daily
					WHERE f.userid = {$flags['info']['userid']}
					AND f.leagueid = leagues_daily.leagueid
					AND home = 1
					GROUP BY home", $dbh)) die ('home=home'.mysql_error());
				if (!mysql_query("REPLACE INTO flags_ranking 
					SELECT f.userid userid, 0, ROUND( SUM( $numactive / activeusers ) ) coolness, COUNT( DISTINCT f.leagueid ) num
					FROM flags_v3 f, leagues_daily
					WHERE f.userid = {$flags['info']['userid']}
					AND f.leagueid = leagues_daily.leagueid
					AND away = 1
					GROUP BY away", $dbh)) die ('home=0'.mysql_error());
				if (!mysql_query("REPLACE INTO flags_ranking
					SELECT userid, 2, ROUND( 2 * SUM( $numactive / activeusers ) ) coolness, COUNT( DISTINCT flags_both.leagueid ) num
					FROM flags_both, leagues_daily
					WHERE flags_both.userid = {$flags['info']['userid']}
					AND flags_both.leagueid = leagues_daily.leagueid
					GROUP BY userid", $dbh)) die ('home=2'.mysql_error());
				if (!mysql_query("REPLACE INTO flags_ranking
					SELECT userid, 3, SUM(coolness), SUM(num) 
					FROM flags_ranking
					WHERE userid = '".$flags['info']['userid']."' AND home < 2
					GROUP BY userid", $dbh)) die('home=3'.mysql_error());
				if (!mysql_query("DELETE FROM flags_semaphore", $dbh)) die ('del_semaphore'.mysql_error());
//			}
		}
	}

	$beenthere = $flags['away'];
	$beenhere = $flags['home'];
}

//else if coming from HoC, check cached data
else if (isset($_GET['tid']) && is_numeric($_GET['tid']) && $_GET['tid'] > 0) {
	if (!$query = mysql_query("SELECT teamname, flags_updated.teamid, f.leagueid, f.home FROM flags_v3 f, flags_updated
	WHERE f.userid = flags_updated.userid
	AND teamid = {$_GET['tid']}
	AND (home = 1 OR away = 1)", $dbh)) die ('select teamname'.mysql_error());
	while ($row = mysql_fetch_array($query)) {
		$forteam = "for {$row['teamname']} ({$row['teamid']})";
		if ($row['home'] == 1) $beenhere[$row['leagueid']] = 1;
		if ($row['away'] == 1) $beenthere[$row['leagueid']] = 1;
	}
	if (mysql_num_rows($query) == 0)  $forteam = "- please submit team {$_GET['tid']} below";
	$forteamid = $_GET['tid'];
}

//else eat the cookie
else if ($_POST['ignorecookie'] == 1) {
	for ($i = 0; $i < 200; $i++) {
		if ($_POST["beenthere$i"]) {
			$beenthere[$i] = 1;
		}
		if ($_POST["beenhere$i"]) {
			$beenhere[$i] = 1;
		}
	}
} else if ($_COOKIE["beenthere"] || $_COOKIE["beenhere"]) {
	if ($_COOKIE["beenthere"]) {
		$crumbled_cookie = split("x", $_COOKIE["beenthere"]);
		foreach ($crumbled_cookie as $chunk) {
			$beenthere[$chunk] = 1;
		}
	}
	if ($_COOKIE["beenhere"]) {
		$crumbled_cookie = split("x", $_COOKIE["beenhere"]);
		foreach ($crumbled_cookie as $chunk) {
			$beenhere[$chunk] = 1;
		}
	}
	if ($_COOKIE["forteam"]) $forteam = $_COOKIE["forteam"];
	if ($_COOKIE["forteamid"]) $forteamid = $_COOKIE["forteamid"];
}

//Bake a cookie, and serve it
$cookie = array();
for ($i = 0; $i < 200; $i++) {
	if ($beenthere[$i] > 0) {
		$cookie[] = $i;
	}
}
setcookie("beenthere", implode("x", $cookie), time()+60*60*24*28);

$cookie = array();
for ($i = 0; $i < 200; $i++) {
	if ($beenhere[$i] > 0) {
		$cookie[] = $i;
	}
}
setcookie("beenhere", implode("x", $cookie), time()+60*60*24*28);

setcookie("forteam", $forteam, time()+60*60*24*28);
setcookie("forteamid", $forteamid, time()+60*60*24*28);
/*
	if ((($_COOKIE["beenthere$i"] == 1) and !($_POST['ignorecookie'])) or ($_POST["beenthere" . $i])) {
		setcookie("beenthere$i", "1", time()+60*60*24*28);
	} else {
		setcookie("beenthere$i", "0", time()-3600);
	}
}
*/

?>
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
<title>Maptrick - Hattrick Coolness rating <?php echo $forteam; ?></title>
<script src="breakout.js" language="JavaScript" type="text/javascript">
</script>
</HEAD>
<BODY onload="breakout_of_frame()">
<LINK href="levels.css" rel="stylesheet" type="text/css">
<STYLE>
A.country {
text-decoration: none;
color: black;
}
A:hover {
text-decoration: underline;
}
TABLE {
border: 1px solid black;
border-spacing: 0px;
border-collapse: collapse;
}
TD.graph {
font-size: 9;
font-family: sans-serif;
text-align: center;
}
SPAN.wait {
	font-size: 9;
}

DIV.kader {
border: 1px dotted black;
padding: 10px;
}

IMG.flag {
border: 1px solid black;
}
</STYLE>
<FORM METHOD="post" ACTION="coolness.php">
<INPUT TYPE="hidden" NAME="ignorecookie" VALUE="1">
<?php

$globalactive = 0;
$globalusers = mysql_query("SELECT sum(activeusers) as active FROM leagues_daily WHERE leagueid != 255", $dbh);
$globaluser = mysql_fetch_array($globalusers);
$globalactive = $globaluser['active'];

$divsizes = array();

$query = mysql_query("SELECT * FROM divsizes", $dbh);

while ($row = mysql_fetch_array($query)) {
	$divsizes[$row['level']] = $row['cumsize'];
	$newdivsizes[$row['level']] = $row['newcumsize'];
}

?>
<a href="maptrick.php"><u>back to maptrick</u></a> / <a href="#submit"><u>forward to the submit button</u></a><br /><br />
<?php
display_ad("coolness_top");
echo "<BR/><BR/>\n";

echo "This ranking shows how hard it is to get a flag of a certain Hattrick country on your club page, by chartering a friendly in that country. The rationale behind the coolness rating is, that it is cool to have a flag that is hard to get! For instance, pretty much anyone who would want to get a Swedish flag could get it, even in the first weeks of the cup; however, it could take the most dedicated flaghunter many seasons to conquer flags from countries like Mongolia, Suriname or Armenia. Because of the low number of active users in those leagues, they are the hardest to get a flag from. This is reflected in the coolness rating; it is calculated as the global number of active users ($globalactive) divided by the respective leagues' active users. This means that the less active users a league has, the higher the coolness ratio becomes! <BR/>\n";
echo "If you have any suggestions on how to make the scoring system better, please do contact me at <A HREF=\"mailto:lhoek@science.uva.nl\">lhoek@science.uva.nl</A>!<BR/>\n<BR/>\n";
echo "Many thanks to the <A HREF=\"credits.html\" TARGET=\"_new\">people who have made an effort to promote the Coolness Rating standard <U>(link)</U></A>!</I><BR/>\n<BR/>\n";

echo "If you're looking for statistics on these leagues, individually, click them to look them up in the Maptrick page.<BR/>\n<BR/>\n";
echo "The \"ND\" column shows the minimum number of divisions needed, if no ownerless teams existed in the higher divisions. If the number is higher than the actual number of divisions, then the league is due for expansion; if the number is lower, then it may have been expanded prematurely.<BR/>\n<BR/>\n";

$i = 0;
$score = 0;
$homescore = 0;
$numscored = 0;
$numhomescored = 0;
$coolest = "";
$coolestscore = 0;
$coolesthome = "";
$coolesthomescore = 0;
$totalcool = 0;
$coollist = array();
$countrylist = array();
$homecountrylist = array();
$visited = array();
$hosted = array();
$hardtogetleagues = mysql_query("SELECT
leagues_daily.leagueid leagueid, tlds.tld tld, tlds.ciatld cia, englishname, shortname, season, 
activeusers, waitingusers, numberofonline, numberoflevels, 
CAST(activeusers-active2 AS SIGNED) d2, round((CAST(activeusers-active2 AS SIGNED) / active2)*100,2) p2, 
CAST(activeusers-active14 AS SIGNED) d14, round((CAST(activeusers-active14 AS SIGNED) / active14)*100,2) p14, 
CAST(activeusers-active56 AS SIGNED) d56, round((CAST(activeusers-active56 AS SIGNED) / active56)*100,2) p56, 
CAST(activeusers-active112 AS SIGNED) d112, round((CAST(activeusers-active112 AS SIGNED) / active112)*100,2) p112, 
CAST(activeusers-active224 AS SIGNED) d224, round((CAST(activeusers-active224 AS SIGNED) / active224)*100,2) p224,
CAST(activeusers-active336 AS SIGNED) d336, round((CAST(activeusers-active336 AS SIGNED) / active336)*100,2) p336 
FROM leagues_daily, tlds, history_n 
WHERE leagues_daily.leagueid = tlds.leagueid AND leagues_daily.leagueid = history_n.leagueid 
AND leagues_daily.leagueid != 255 
ORDER BY activeusers ASC, season DESC, waitingusers ASC, numberofonline ASC", $dbh);

echo "<TABLE border=1>\n\t<TR><TD COLSPAN=\"5\"><TD COLSPAN=\"7\"><B>Active users / Tendency over time (d=days, w=weeks)</B><TD COLSPAN=\"3\">\n\t<TR><TD><B>Div</B></TD><TD><B>ND</B><TD><B>English / local country name (country code)</B></TD><TD><B>Flag</B></TD><TD><B>Season<B></TD><TD>Active <span class=\"wait\">+w</span></TD><TD>T-2d</TD><TD>T-2w</TD><TD>T-8w</TD><TD>T-16w</TD><TD>T-32w</TD><TD>T-48w</TD><TD><B>Coolness index</B></TD><TD ALIGN=\"center\">Vi</TD><TD ALIGN=\"center\">Ho</TD></TR>\n";
while ($hardtogetleague = mysql_fetch_array($hardtogetleagues)) {
$i++;
if ($hardtogetleague['activeusers'] > 0) {
	$coolness = round($globalactive / $hardtogetleague['activeusers'], 2);
} else {
	$coolness = "infinite";
}
if ($beenthere[$hardtogetleague['leagueid']] == 1) {
	$visited[] = $hardtogetleague['leagueid'];
	$countrylist[] = $hardtogetleague['tld'];
}
if ($beenhere[$hardtogetleague['leagueid']] == 1) {
	$hosted[] = $hardtogetleague['leagueid'];
	$homecountrylist[] = $hardtogetleague['tld'];
}
if (($coolness > $coolestscore) && $beenthere[$hardtogetleague['leagueid']]) {
	$coolestscore = $coolness;
	$coolest = $hardtogetleague['englishname'];
}
if (($coolness > $coolesthomescore) && $beenhere[$hardtogetleague['leagueid']]) {
	$coolesthomescore = $coolness;
	$coolesthome = $hardtogetleague['englishname'];
}
/*	if ($coolness > 20000) {
		$denom = "Brand spanking cool!";
	} else if ($coolness > 10000) {
		$denom = "Divinely cool";
	} else {
		$denom = "Could be cooler";
	}
*/
	echo "\t<TR";
	if ($beenthere[$hardtogetleague['leagueid']] && $beenhere[$hardtogetleague['leagueid']]) {echo " bgcolor=\"#C0FFC0\"";}
	else if ($beenthere[$hardtogetleague['leagueid']]) {echo " bgcolor=\"#C0C0FF\"";}
	else if ($beenhere[$hardtogetleague['leagueid']]) {echo " bgcolor=\"#FFFFC0\"";}
	$totalusers = $hardtogetleague['activeusers'] + $hardtogetleague['waitingusers'];

	$needlevel = 1;
	for ($n = 1; $n <= 11; $n++) {
		if ($totalusers > $divsizes[$n]) {
			$needlevel = $n+1;
		}
	}
	
	$futureneedlevel = 1;
	for ($n = 1; $n <= 15; $n++) {
		if ($totalusers > $newdivsizes[$n]) {
			$futureneedlevel = $n+1;
		}
	}

echo "><TD CLASS=\"s{$hardtogetleague['numberoflevels']}new\">{$hardtogetleague['numberoflevels']}</TD>
<TD CLASS=\"s{$futureneedlevel}new\">$futureneedlevel
<TD>$i. <a class=\"country\" href=\"maptrick.php?leagueid={$hardtogetleague['leagueid']}\">{$hardtogetleague['englishname']} / {$hardtogetleague['shortname']}</a> ({$hardtogetleague['tld']})</TD>
<TD ALIGN=\"center\"";

if ($hardtogetleague['leagueid'] == 14 && time() < 1152561600) echo " style=\"background-color: #FFC060\"";

echo "><A HREF=\"https://www.cia.gov/library/publications/the-world-factbook/flags/{$hardtogetleague['cia']}-flag.html\" TARGET=\"_new\"><IMG CLASS=\"flag\" SRC=\"http://flags.alltidhattrick.org/images/{$hardtogetleague['leagueid']}flag.gif\" height=\"12\" width=\"20\"></A></TD>
<TD ALIGN=\"center\">{$hardtogetleague['season']}</TD><TD ALIGN=\"center\">{$hardtogetleague['activeusers']} <span class=\"wait\">+{$hardtogetleague['waitingusers']}</span></TD>";
	$as = array(2, 14, 56, 112, 224, 336);
	foreach ($as as $a) {
		echo "<TD CLASS=\"graph\" BGCOLOR=\"";
		if ($hardtogetleague["p$a"] == 0) {
			echo "#FFFFFF";
		} else if ($hardtogetleague["p$a"] >= 100) {
			echo "#00FF00";
		} else if ($hardtogetleague["p$a"] < -50) {
			echo "#FF0000";
		} else if ($hardtogetleague["p$a"] < 0) {
			$tint = 255-round(-2.54*2*$hardtogetleague["p$a"]);
			printf("#FF%02X%02X", $tint, $tint);
		} else if ($hardtogetleague["p$a"] > 0) {
			$tint = 255-round(2.54*$hardtogetleague["p$a"]);
#			$tint = 255-round(); // do something with logarithm
			printf("#%02XFF%02X", $tint, $tint);
		} else {
			echo "#000000";
		}
		echo "\">";
		if ($hardtogetleague["d$a"] < $hardtogetleague['activeusers']) {
			if ($hardtogetleague["d$a"] >= 0) {echo "+";}
			echo "{$hardtogetleague["d$a"]}<BR/>(";
			if ($hardtogetleague["d$a"] == 0) {echo "0%)";}
			else {echo "{$hardtogetleague["p$a"]}%)";}
		}
	}
	echo "<TD>$coolness</TD><TD><INPUT TYPE=\"checkbox\" NAME=\"beenthere{$hardtogetleague['leagueid']}\" VALUE=\"1\"";
	if ($beenthere[$hardtogetleague['leagueid']]) {
		echo " CHECKED";
		$score+=$coolness;
		$numscored++;
	}
	echo "></TD>";
	echo "<TD><INPUT TYPE=\"checkbox\" NAME=\"beenhere{$hardtogetleague['leagueid']}\" VALUE=\"1\"";
	if ($beenhere[$hardtogetleague['leagueid']]) {
		echo " CHECKED";
		$homescore+=$coolness;
		$numhomescored++;
	}
	echo "></TD></TR>\n";
	$totalcool += $coolness;
	$coollist[] = $coolness;
}

$totalcool = round(($totalcool), 2);
$score = round($score, 1);
$homescore = round($homescore, 1);

$coolmapopts = "";

foreach ($visited as $visit) {
	$coolmapopts .= "v[]=$visit&";
}

foreach ($hosted as $host) {
	$coolmapopts .= "h[]=$host&";
}
?>
</table><br />
<a name="submit"></a>
<input type="submit" value="Update your Coolness score manually" />
</form> 
<?php
display_ad("coolness_mid");
?>
or update your flags automatically (this also updates your team in the <b><a href="hallofcool.php">Hall of Cool</a></b>):<br /> 
<form method="POST" action="coolness.php"><br />
User name: <input name="login" size="15"> Security code <i>(not password!)</i>: <input name="seccode" type="password" size="15">
<input type="submit" value="login"> (May fail if HT is very busy!)<br /><br />
<?php if (isset($_COOKIE["own_teamid"])) {
	if (!$query = mysql_query("SELECT * FROM flags_updated WHERE teamid = {$_COOKIE["own_teamid"]}", $dbh)) die (mysql_error());
	$row = mysql_fetch_array($query);
	echo "If Hattrick is not responding, or you know that your data has not changed since {$row['FetchedDate']}, <a href=\"coolness.php?tid={$_COOKIE["own_teamid"]}#submit\"> retrieve the cached data for {$row['TeamName']}</a>.<br />\n";
	echo "Also, if you want to get a new flag easily, try the new <a href=\"challenge_suggester.php?teamid={$_COOKIE["own_teamid"]}\">Challenge suggester</a>!<br /><br />\n";
}
?>
<i><b>Optional:</b> enter Team ID to check another team (<b>Also fill in the two fields above</b>):</i> 
<input name="teamid" size="15"<?php if (isset($_GET['tid']) && is_numeric($_GET['tid'])) { echo " value=\"{$_GET['tid']}\""; } ?>><br /></form><br />
The Coolness calculator is part of Maptrick, which is CHPP certified (ID#: 1045).<br />
<img src="http://static.alltid.org/images/chpp_logotype.gif"/><br /><br />
<?php
display_ad("coolness_bottom");


$chasetypes = array(
        "0" => "Away",
        "1" => "Home",
        "2" => "Away AND Home",
        "3" => "Away PLUS Home"
);

$sorts = array("coolness", "num");

if (isset($forteamid) && $forteamid > 0) {
	showHocRankBox($forteamid,$dbh);
}

echo "<IMG SRC=\"coolmap.php?$coolmapopts\" ALT=\"Map of visited and hosted countries\"/>";
#echo "<IMG SRC=\"http://maptrick.nl.eu.org/coolmap.php?$coolmapopts\" ALT=\"Map of visited and hosted countries\"/>";
#echo "<IMG SRC=\"coolmap.php?$coolmapopts\" ALT=\"Map of visited and hosted countries\"/>";
echo "<BR/><BR/>";

echo "<hr>\n";
echo "Coolness score based on countries currently visited: $score ($numscored countries)<br/>\n";
if ($coolestscore > 0) {
	echo "Countries visited: ";
	sort($countrylist);
	$poscool = 0;
	$numcountries = count($countrylist);
	for ($counter = 0; $counter < $numcountries; $counter++) {
		echo "$countrylist[$counter]";
		$poscool += $coollist[$counter];
		if ($counter < $numcountries-1) {echo " ";}
	}
	echo "<BR/>\n";
	$coolestpart = round((round($coolestscore,1) / $score) * 100, 1);
	echo "The coolest country you have visited is $coolest, which is responsible for $coolestpart% of your total score.<br/>\n";
}
echo "<br/>\nCoolness score based on countries currently hosted: $homescore ($numhomescored countries)<br/>\n";

if ($coolesthomescore > 0) {
	echo "Countries hosted: ";
	sort($homecountrylist);
	$poshomecool = 0;
	$numhomecountries = count($homecountrylist);
	for ($counter = 0; $counter < $numhomecountries; $counter++) {
		echo "$homecountrylist[$counter]";
		$poshomecool += $coollist[$counter];
		if ($counter < $numhomecountries-1) {echo " ";}
	}
	echo "<BR/>\n";
	$coolesthomepart = round((round($coolesthomescore,1) / $homescore) * 100, 1);
	echo "The coolest country you have hosted is $coolesthome, which is responsible for $coolesthomepart% of your total score.<br/>\n<br/>\n";
}

if ($coolestscore > 0 && $coolesthomescore > 0) {
	$averagecool = round ($score / $numscored);
	$averagemanagers = round ($globalactive / ($score / $numscored));
	$averageleague = "nowhere";
	$averageleagues = mysql_query("SELECT englishname FROM leagues_daily WHERE activeusers <= $averagemanagers ORDER BY activeusers DESC LIMIT 1", $dbh);
	while ($field = mysql_fetch_array($averageleagues)) {
		$averageleague = $field['englishname'];
	}
	$averagehomecool = round ($homescore / $numhomescored);
	$averagehomemanagers = round ($globalactive / ($homescore / $numhomescored));
	$averagehomeleague = "nowhere";
	$averagehomeleagues = mysql_query("SELECT englishname FROM leagues_daily WHERE activeusers <= $averagehomemanagers ORDER BY activeusers DESC LIMIT 1", $dbh);
	while ($field = mysql_fetch_array($averagehomeleagues)) {
		$averagehomeleague = $field['englishname'];
	}

	echo "Your average coolness is $averagecool; this puts you on or below $averageleague.<BR/>\n";
	if ($poscool > 0) {
		$efficiency = 100*round($score/$poscool, 3);
		echo "Your efficiency ratio is $efficiency% (Coolness ratio is $score out of $poscool possible with $numcountries countries).<BR/>\n";
	}
	echo "For home matches, Your average coolness is $averagehomecool; this puts you on or below $averagehomeleague.<BR/>\n";
	if ($poshomecool > 0) {
		$homeefficiency = 100*round($homescore/$poshomecool, 3);
		echo "Your efficiency ratio at home is $homeefficiency% (Coolness ratio is $homescore out of $poshomecool possible with $numhomecountries countries hosted).<BR/>\n";
	}
}
$progress = round(($score / $totalcool) * 100, 1);
$homeprogress = round(($homescore / $totalcool) * 100, 1);
echo "The sum of all scores is $totalcool; currently, your score is $progress% of this sum for away matches and $homeprogress% for home matches.<br/>\n<br/>\n";

echo "Check the countries where you have played <B>FRIENDLY</B> matches, click the button, put the score in your signature and show how cool you are! If you have never played a friendly away match in your home country, you are not allowed to add it <I>(this is a change of the rules - previously, you were not allowed to put your own country in at all)</I>.<br/>\n";
echo "To help spread this ratings standard, also put a link to this page in your signature; cut and paste the following: <PRE>>>>How [b][u]cool[/u][/b] are you? [link=http://maptrick.nl.eu.org/coolness.php]<<<</PRE><br/>\n";
?>
<BR><BR>
Also, you can use the following graphic on your homepage - Big kudos to <B>mindw0rm</B> for creating this little jewel!<BR><BR>
<A HREF="coolness.php"><IMG BORDER="0" SRC="coolness_logo.jpg"/></A><BR><BR>
This HTML code will create the above example:<BR/>
&lt;A HREF="http://maptrick.nl.eu.org/coolness.php"&gt;&lt;IMG BORDER="0" SRC="http://websec.science.uva.nl/~lhoek/coolness_logo.jpg"/&gt;&lt;/A&gt<BR/>
<BR/>
150x150version:<BR/>
<IMG SRC="coolness_logo_150.jpg"/>
<BR/><BR/>
120x120 version:<BR/>
<IMG SRC="coolness_logo_120.jpg"/>
<BR/><BR/>
<DIV class="kader">
<script type="text/javascript"><!--
google_ad_client = "pub-7956987225901689";
google_ad_width = 468;
google_ad_height = 60;
google_ad_format = "468x60_as_rimg";
google_cpa_choice = "CAAQj6eVzgEaCIxA5niBniDSKOm293M";
//--></script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</DIV>
<?php urchin(); ?>
</BODY>
</HTML>
